// 
// ObserverMap.ts
// Author:qiuchun(362460803@qq.com)
// Time:2023.05.09 17:29:20
// Desc:观察者管理类
//

import Notification from "./Notification";
import Notifier from "./Notifier";
import Observer from "./Observer";


export default class ObserverMap {
    private _map = new Map<string, Observer[]>();

    public initialize(): void {

    }

    //注册观察者
    public registerObserver(notificationName: string, observer: Observer) {
        let observers = this._map.get(notificationName);
        if (observers) {
            observers.push(observer);
        } else {
            let newObservers = [
                observer
            ];
            this._map.set(notificationName, newObservers);
        }
    };

    //移除观察者
    public removeObserver(notificationName: string, notifyContext: Notifier) {
        let observers = this._map.get(notificationName);
        if (observers == null) {
            return;
        }

        let i = observers.length;
        while (i--) {
            let observer = observers[i];
            if (observer.compareNotifyContext(notifyContext)) {
                observers.splice(i, 1);
                break;
            }
        }

        //数组长度0，则删除元素
        if (observers.length == 0) {
            this._map.delete(notificationName);
        }
    };

    //通知观察者
    //@param: notification,消息包
    //@param: dest,接收者，没有接收者则广播
    notifyObservers(notification: Notification, dest?: Notifier | string) {
        let notificationName = notification.getName();
        let observersRef = this._map.get(notificationName);
        if (observersRef) {
            let observers = observersRef.slice(0);
            let len = observers.length;
            for (let i = 0; i < len; i++) {
                let observer = observers[i];
                if (observer == null) {
                    console.error("mvp error: i = " + i + ", oberver is null")
                    continue;
                }
                //有接受者
                if (dest) {
                    if (observer.compareNotifyContext(dest) == true) {
                        observer.notifyObserver(notification);
                        break;
                    }
                }
                //无接受者则广播
                else {
                    observer.notifyObserver(notification);
                }
            }
        }
    };

    static instance: ObserverMap;
    static getInstance(): ObserverMap {
        if (this.instance == null) {
            this.instance = new ObserverMap();
        }
        return this.instance;
    }



}